package com.sumainfor.pc.gmio.service.impl;

import com.qiniu.util.Json;
import com.sumainfor.common.Constants;
import com.sumainfor.common.entity.TemplateData;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.DateUtils;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.*;
import com.sumainfor.common.wechat.WeChatConfig;
import com.sumainfor.pc.gmio.dao.HoPooledMapper;
import com.sumainfor.pc.gmio.dao.HoWaterMeterMapper;
import com.sumainfor.pc.gmio.dao.MktFeign.BillOwnerMapper;
import com.sumainfor.pc.gmio.dao.SeTenantBillMapper;
import com.sumainfor.pc.gmio.dao.UtilsMapper;
import com.sumainfor.pc.gmio.feign.Zfeign.ZpcMktFeign;
import com.sumainfor.pc.gmio.feign.Zfeign.ZwxTenantFeign;
import com.sumainfor.pc.gmio.service.SeWaterMeterExtService;
import javassist.expr.NewArray;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.management.ObjectName;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zc
 * @ClassName SeWaterMeterExtServiceImpl
 * @date 2019/11/21 14:45
 * @description: TODO
 */
@Service
public class SeWaterMeterExtServiceImpl implements SeWaterMeterExtService {
    private ReentrantLock lock = new ReentrantLock(false);
    Logger log = LoggerFactory.getLogger(SeWaterMeterExtServiceImpl.class);

    @Autowired
    ZpcMktFeign zpcMktFeign;

    @Autowired
    HoWaterMeterMapper hoWaterMeterMapper;


    @Autowired
    HoPooledMapper hoPooledMapper;

    @Autowired
    UtilsMapper utilsMapper;

    @Autowired
    SeTenantBillMapper seTenantBillMapper;

    @Autowired
    BillOwnerMapper billOwnerMapper;

    @Autowired
    ZwxTenantFeign zwxTenantFeign;


    /**
     * 需要管家抄水表的房源
     * @param params
     * @return
     */
    @Override
    public JsonResult getWatMeterNum(Map<String, Object> params, Pager pager) {


        List<String> MeterRoleList = new ArrayList<>();//最近一次抄表为租赁顾问或者管家的抄表
        MeterRoleList.add("0");
        MeterRoleList.add("2");
        JsonResult MktFeign = zpcMktFeign.getPactNumHou(params,pager);//获取需要管家抄表的房源集合
        Map<String,Object> MktMap = (Map<String, Object>) MktFeign.get("result");
        List<Map<String,Object>> MktList = (List<Map<String, Object>>) MktMap.get("dataList");
        if(MktList.size()>0){
            for (Map<String,Object> map1:MktList){
                map1.put("MeterRoleList",MeterRoleList);
                Map<String,Object> hoWaterMeterMap = hoWaterMeterMapper.getHouInfoMater(map1);//查询当前房源的最近一次(租赁顾问或者管家)的抄表数;
                if (hoWaterMeterMap!=null){
                map1.putAll(hoWaterMeterMap);
                }
            }
        }

     return MktFeign;
    }

    /**
     * 秘书抄房源下的水表
     * @param params
     * @param pager
     * @return
     */
    @Override
    public JsonResult getWatSecretary(Map<String, Object> params, Pager pager) {
        JsonResult MktFeign = zpcMktFeign.getHouId(params,pager);//获取需要秘书抄表的房源集合
        Map<String,Object> MktMap = (Map<String, Object>) MktFeign.get("result");
        List<Map<String,Object>> MktList = (List<Map<String, Object>>) MktMap.get("dataList");
        if(MktList.size()>0){
            for (Map<String,Object> map1:MktList){
                map1.put("MeterRole",1);
                Map<String,Object> hoWaterMeterMap = hoWaterMeterMapper.getHouInfoMater(map1);//查询当前房源的最近一次的抄表数;
                if (hoWaterMeterMap!=null) {
                    map1.putAll(hoWaterMeterMap);
                }
                String a = MapUtils.getString(map1,"HouInfoId");
                map1.put("HouInfoId",a.replace(a.substring(a.length() - 1, a.length()), "Z"));
            }
        }
        return MktFeign;



    }

    /**
     * 管家录入水费集合
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult getWatBrowse(Map<String, Object> params) {

        JsonResult result = new JsonResult();
//
//        参数格式
//                params:{
//
//                  WatHouList:[
//                          {
//                                   HouId
//                                   HouInfoId
//                                  LastMonthRead
//                                  ThisMonthRead
//                          }
//
//
//
//
//                          ]
//
//
//                }

        /**
         * 加锁操作
         */
        lock.lock();
        try {




//
//            String WatUUID = "";//水抄表编号
//            String WatUUIDS="";//公摊水抄表编号
//            String Watus = "";//水抄表批次编号
//            //获取账单编号
//            Map<String, Object> BiIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
//                put("uuid", "BiId");
//                put("database", Constants.DATA_SOURCE_GMIO);
//                put("surface", "tcgmio_tenant_bill");
//            }});
//
//
//            //水
//            Map<String,Object>Watuuid=utilsMapper.getUUID(new HashMap<String,Object>(){{
//                put("uuid", "WameId");
//                put("database", Constants.DATA_SOURCE_GMIO);
//                put("surface", "tcgmio_water_meter");
//            }});
//            //公摊水
//            Map<String,Object>Watuuidss=utilsMapper.getUUID(new HashMap<String,Object>(){{
//                put("uuid", "WatPooledId");
//                put("database", Constants.DATA_SOURCE_GMIO);
//                put("surface", "tcgmio_water_meter_Pooled");
//            }});
//
//            if(Watuuid!=null){
//                int number=Integer.valueOf(Watuuid.get("uuid").toString());
//                WatUUID= ComUtils.getLocalTrmSeqNum("WM0",number);
//                Watus = ComUtils.getLocalTrmSeqNum("BA0",number);
//            }else{
//                WatUUID=ComUtils.getLocalTrmSeqNum("WM0",0);
//                Watus = ComUtils.getLocalTrmSeqNum("BA0",0);
//            }

            //获取当前时间
            Date nowTime = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String GenerateTimeNow = sdf.format(nowTime);//租赁顾问签约抄水电燃,抄表记录的时间默认一致,

            //账单生成日
            DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
            Date date = format1.parse(GenerateTimeNow);

            List<Map<String,Object>> WatHouList = (List<Map<String, Object>>) params.get("WatHouList");//获取本次抄表房源集合
            if(WatHouList.size()>0){
                for (Map<String,Object> map1:WatHouList){


                    String WatUUID = "";//水抄表编号
                    String Watus = "";//水抄表批次编号
                    //水
                    Map<String,Object>Watuuid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                        put("uuid", "WameId");
                        put("database", Constants.DATA_SOURCE_GMIO);
                        put("surface", "tcgmio_water_meter");
                    }});
                    if(Watuuid!=null){
                        int number=Integer.valueOf(Watuuid.get("uuid").toString());
                        WatUUID= ComUtils.getLocalTrmSeqNum("WM0",number);
                        Watus = ComUtils.getLocalTrmSeqNum("BA0",number);
                    }else{
                        WatUUID=ComUtils.getLocalTrmSeqNum("WM0",0);
                        Watus = ComUtils.getLocalTrmSeqNum("BA0",0);
                    }




                    //记录本次抄表数
                    Double WatPooled = new Double("0");//本次抄表在租房间的公摊度数
                    double ThisMonthRead =  MapUtils.getDouble(map1,"ThisMonthRead");//本次抄表数
                    double LastMonthRead = MapUtils.getDouble(map1,"LastMonthRead");//上次抄表数
                    //本次抄表一共需要生成的账单金额
                    Double billMoney = new Double("0");//本次一共需要产生的账单金额


                    List<Map<String,Object>> getHouPact =  zpcMktFeign.getHouPact(map1);//当前房源在租租客
                    if (getHouPact.size()>0){
                        WatPooled =CompuUtils.div(CompuUtils.reduce(ThisMonthRead,LastMonthRead),new Double(getHouPact.size()),2);//本次管家抄表,房源的公摊费用
                    }


                    for (Map<String,Object> map3:getHouPact) {//查询管家抄表时房源所租租客,遍历每一个租客,找到租客的公摊表
                        Map<String,Object> billMap = new HashMap<>();
                        String  BiIdUUID = "";//水费账单编号
                        //获取账单编号
                        Map<String, Object> BiIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                            put("uuid", "BiId");
                            put("database", Constants.DATA_SOURCE_GMIO);
                            put("surface", "tcgmio_tenant_bill");
                        }});
                        if(BiIduuid!=null){
                            int number=Integer.valueOf(BiIduuid.get("uuid").toString());
                            BiIdUUID= ComUtils.getLocalTrmSeqNum("BIWATGJ",number);

                        }else{
                            BiIdUUID=ComUtils.getLocalTrmSeqNum("BIWATGJ",0);
                        }
                        billMap.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                        billMap.put("fnc",
                                this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                        ParamsCommon.commonInsertParms(billMap);

                        StringBuffer BillExpains = new StringBuffer();
                        Double beforePooled =CompuUtils.mul(MapUtils.getDouble(map3,"WaterPricing"),WatPooled);//每个租客的公摊费用



                        List<Map<String,Object>> getPooledList=hoPooledMapper.getPooledList(map3);//查询租客未生成账单的公摊费用
                        if (getPooledList.size()>0){//表示本次抄表之前有公摊费用未生成账单,要加上之前的公摊费用一起生成账单,

                            for (Map<String,Object> map2:getPooledList){
                                beforePooled = CompuUtils.add(beforePooled,MapUtils.getDouble(map2,"WatMetMoney"));
                                BillExpains.append(MapUtils.getString(map2,"WatPooledId"));
                                BillExpains.append(";");

                                //修改公摊费用为已生成账单
                                Map<String,Object> PoolMap = new HashMap<>();
                                PoolMap.put("term","4");//1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                                PoolMap.put("fnc",
                                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                                ParamsCommon.commonUpdateParms(PoolMap);
                                PoolMap.put("WatPooledId",map2.get("WatPooledId"));//公摊账单编号
                                PoolMap.put("Status",1);//租客水费公摊表已生成账单
                                PoolMap.put("IfGenerate",1);//水抄表已生成账单
                                Integer a1 = hoPooledMapper.updateWatPooled(PoolMap);
                                if (a1>0){
                                   result.putSuccess("新增成功");

                                }else{
                                    return result.putFailed("修改租客公摊表失败");
                                }

//                                Integer a2 = hoWaterMeterMapper.updateHoWaterDelfg(PoolMap);
//                                if (a1>0){
//
//                                }else{
//                                    return result.putFailed("修改租客公摊表失败");
//                                }
                                //待定


                            }
                        }

                            billMap.put("BiId",BiIdUUID);//账单编号
                            billMap.put("CorId",map3.get("CorId"));//账单归属公司
                            billMap.put("BiName","管家抄表生成租客水费账单");//账单名称
                            billMap.put("IfTemporary",0);//是否是临时账单0否 1 是
                            billMap.put("BiType",2);//账单类型 2公共事业费
                            billMap.put("Source",WatUUID);//账单来源
                            billMap.put("PubType",1);//公共事业费类型1水费
                            billMap.put("BiMoney",beforePooled);//账单金额,每个租客本次抄表需支付金额
                            billMap.put("BillExplain",BillExpains.toString());//账单金额说明
                           // billMap.put("BiGenerated",GenerateTimeNow);//账单生成日
                            // billMap.put("EndTime",DateUtils.addDateDays(date,15));//账单结束日
                            billMap.put("BiGenerated",map1.get("GenerateTime"));//账单生成日
                             billMap.put("EndTime",GenerateTimeNow);//账单结束日
                            billMap.put("LateDay", DateUtils.addDateDays(date,15));//账单最晚付款日
                            billMap.put("TenId",map3.get("TenId"));//租客编号
                            billMap.put("HouId",map3.get("HouId"));//房源编号
                            billMap.put("HouInfoId",map3.get("HouInfoId"));//房源详表编号
                            billMap.put("CreateType",2);//账单创建人类型1系统 2 人为
                            billMap.put("Create",ContextUtils.getUserId());//账单创建人
                            billMap.put("ExpTime",DateUtils.addDateDays(date,15));//逾期开始时间
                            billMap.put("Status",1);//1待支付
                            Integer a3 = seTenantBillMapper.addTenantBill(billMap);//新增水费账单
                              if (a3>0){
                                  result.putSuccess("新增成功");

                                  JsonResult OpenResult = zwxTenantFeign.getTenOpenId(billMap);
                                  Map<String,Object> ceshiMap = (Map<String, Object>) OpenResult.get("result");
                                  //推送微信模板
                                  String touser=ceshiMap.get("uopid").toString();//租客的openid
                                  Map<String, TemplateData> param = new HashMap<>();
                                  param.put("first", new TemplateData("唐巢公寓温馨提示：尊敬的租客，您有新的待支付的水费账单。请您尽快支付。如有异议，请联系您的租赁顾问人员为您服务。\n", "#4876FF"));
                                  param.put("keyword1", new TemplateData(billMap.get("BiGenerated").toString(), "#4876FF"));//账单日期
                                  param.put("keyword2", new TemplateData("0", "#4876FF"));//逾期天数
                                  param.put("keyword3", new TemplateData(billMap.get("BiGenerated").toString()+"-"+billMap.get("LateDay").toString(), "#4876FF"));//账单周期
                                  param.put("keyword4", new TemplateData(billMap.get("BiMoney").toString(), "#4876FF"));//应缴明细
                                  log.info("param:"+net.sf.json.JSONObject.fromObject(param));
                                  Jsapi_ticketUtil.sendTemplate(touser, WeChatConfig.GUANMI_ID,"http://www.4006269069.net/#/allBill","#4876FF", net.sf.json.JSONObject.fromObject(param));









                              }else{
                                    return result.putFailed("新增水费账单表失败");
                                }

                            billMoney = CompuUtils.add(billMoney,beforePooled);//一个租客的账单

                    }
                    //将本次抄表数记录在水费抄表记录中,并记录在公摊表中
                    Map<String,Object> Watmap = new HashMap<>();
                    Watmap.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                    Watmap.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(Watmap);
                    Watmap.put("WameId",WatUUID);//水费抄表编号
                    Watmap.put("BatchId",Watus);//水费抄表批次编号
                    Watmap.put("HouId",map1.get("HouId"));//房源编号
                    Watmap.put("HouInfoId", map1.get("HouInfoId"));//房源详表编号
                    Watmap.put("IfOperaType",1);//是否整租 0否 1是 2秘书抄表
                    Watmap.put("StaTime",map1.get("GenerateTime"));//账单起时间
                    Watmap.put("EndTime",GenerateTimeNow);//账单止时间
                    Watmap.put("LastMonthRead",map1.get("LastMonthRead"));//上月总表数
                    Watmap.put("ThisMonthRead", map1.get("ThisMonthRead"));//本次总表数
                    Watmap.put("MeterRole",2);//抄表人角色0租赁顾问 1服务秘书 2服务管家
                    Watmap.put("BillMoney",billMoney);//账单金额.所有租客一共需支付的金额
                    Watmap.put("GenerateTime",GenerateTimeNow);//抄表日期
                    Watmap.put("Recorder", ContextUtils.getUserId());//记录人编号
                    Watmap.put("IfApportion",1);//是否需要分摊0否 1是
                    Watmap.put("IfGenerate",1);//是否生成账单 0未生成 1已生成
                    Integer a4 = hoWaterMeterMapper.addHoWaterMeter(Watmap);//本次管家抄表记录水抄表
                    if (a4>0){
                        result.putSuccess("新增成功");
                    }else{
                        return result.putFailed("新增水抄表失败");
                    }

                    for (Map<String,Object> PoMap:getHouPact){//遍历在租租客编号


                        String WatUUIDS="";//公摊水抄表编号


                        //公摊水
                        Map<String,Object>Watuuidss=utilsMapper.getUUID(new HashMap<String,Object>(){{
                            put("uuid", "WatPooledId");
                            put("database", Constants.DATA_SOURCE_GMIO);
                            put("surface", "tcgmio_water_meter_Pooled");
                        }});

                        Map<String,Object> WatPolMap = new HashMap<>();
                         WatPolMap.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                         WatPolMap.put("fnc",
                                 this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                         ParamsCommon.commonInsertParms(WatPolMap);
                         if (Watuuidss != null) {
                             int number = Integer.valueOf(Watuuidss.get("uuid").toString());
                             WatUUIDS = ComUtils.getLocalTrmSeqNum("WP", number);
                         } else {
                             WatUUIDS = ComUtils.getLocalTrmSeqNum("WP", 0);
                         }
                         WatPolMap.put("WatPooledId", WatUUIDS);//公摊水表编号
                         WatPolMap.put("WameId", Watmap.get("WameId"));//水抄表编号
                         WatPolMap.put("BatchId", Watmap.get("BatchId"));//水抄表批次编号
                         WatPolMap.put("TenId", PoMap.get("TenId"));//租客编号
                         WatPolMap.put("HouId", PoMap.get("HouId"));//房源编号
                         WatPolMap.put("HouInfoId", PoMap.get("HouInfoId"));//房源详表编号
                         WatPolMap.put("WatPooled", WatPooled);//公摊用水量
                         WatPolMap.put("WatMetMoney",CompuUtils.mul(MapUtils.getDouble(PoMap,"WaterPricing"),WatPooled));//记录在租房间的公摊水费
                         WatPolMap.put("PoolTime", GenerateTimeNow);//公摊生成时间
                         WatPolMap.put("Status", 1);//是否生成账单0未生成1已生成
                         Integer a5 = hoPooledMapper.addWatPooled(WatPolMap);//新增本次抄表每个房间的的公摊费用
                        if (a5>0){
                            result.putSuccess("新增成功");
                        }else{
                            return result.putFailed("新增水抄表失败");
                        }


                     }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事物回滚
        } finally {
            lock.unlock();//释放
        }

        return result;
    }

    /**
     * 秘书抄水费
     * @param params
     * @return
     */
    @Override
    public JsonResult addWatClerk(Map<String, Object> params) {
    JsonResult result = new JsonResult();
//
//        参数格式
//                params:{
//                 "WatHouList":[
//                    {
//                        HouId
//                        HouInfoId
//                        LastMonthRead
//                        ThisMonthRead
//                        StaTime
//                        EndTime
//                        BillMoney
//                    }, {
//                        HouId
//                                HouInfoId
//                        LastMonthRead
//                                ThisMonthRead
//                        StaTime
//                                EndTime
//                        BillMoney
//                    }
//
//                         ]
//
//
//                }




        lock.lock();
        try {

//            String BiOutIdUUID = "";//账单支出编号
//            String  BiIdUUID ="";//租客编号
//            String WatmeIdUUID = "";//水费抄表编号
//            String BatchIdUUID = "";//水费抄表批次编号
//            Map<String, Object> BiOutIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
//                put("uuid", "BiOutId");
//                put("database", Constants.DATA_SOURCE_GMIO);
//                put("surface", "tcgmio_bill_outlay");
//            }});
//            String  BiIdUUID ="";//租客编号
//            Map<String, Object> BiIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
//                put("uuid", "BiId");
//                put("database", Constants.DATA_SOURCE_GMIO);
//                put("surface", "tcgmio_tenant_bill");
//            }});



//            String WatmeIdUUID = "";//水费抄表编号
//            String BatchIdUUID = "";//水费抄表批次编号
//            Map<String, Object> WameIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
//                put("uuid", "WameId");
//                put("database", Constants.DATA_SOURCE_GMIO);
//                put("surface", "tcgmio_water_meter");
//            }});
//
//            if(WameIduuid!=null){
//                int number=Integer.valueOf(WameIduuid.get("uuid").toString());
//                WatmeIdUUID= ComUtils.getLocalTrmSeqNum("WM0",number);
//                BatchIdUUID = ComUtils.getLocalTrmSeqNum("BA0",number);
//            }else{
//                WatmeIdUUID=ComUtils.getLocalTrmSeqNum("WM0",0);
//                BatchIdUUID = ComUtils.getLocalTrmSeqNum("BA0",0);
//            }

            Date nowTime = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String GenerateTimes = sdf.format(nowTime);//记录当前时间



            Integer a = new Integer("0");
            List<Map<String,Object>> WatHouList = (List<Map<String, Object>>) params.get("WatHouList");//获取本次秘书抄表的房源水表集合
            if (WatHouList.size()>0){
                for (Map<String,Object> WatHouMap:WatHouList){



                    String WatmeIdUUID = "";//水费抄表编号
                    String BatchIdUUID = "";//水费抄表批次编号
                    Map<String, Object> WameIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                        put("uuid", "WameId");
                        put("database", Constants.DATA_SOURCE_GMIO);
                        put("surface", "tcgmio_water_meter");
                    }});

                    if(WameIduuid!=null){
                        int number=Integer.valueOf(WameIduuid.get("uuid").toString());
                        WatmeIdUUID= ComUtils.getLocalTrmSeqNum("WM0",number);
                        BatchIdUUID = ComUtils.getLocalTrmSeqNum("BA0",number);
                    }else{
                        WatmeIdUUID=ComUtils.getLocalTrmSeqNum("WM0",0);
                        BatchIdUUID = ComUtils.getLocalTrmSeqNum("BA0",0);
                    }






                    Integer aaa = new Integer("0");

                    Double GasBiMoney = new Double("0");

                    //获取当前房源签署的公司号
                    JsonResult CorIdResult = zpcMktFeign.getCorId(WatHouMap);
                    Map<String,Object> CorIdMap = (Map<String, Object>) CorIdResult.get("result");


                    //判断当前房源是否在出租中
                    JsonResult MktResult = zpcMktFeign.getInfoStatus(WatHouMap);
                    Map<String,Object> getInfoMap = (Map<String, Object>) MktResult.get("result");



                    Map<String,Object> OutLaymap = new HashMap<>();
                    String BiOutIdUUID = "";//账单支出编号
                    Map<String, Object> BiOutIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                        put("uuid", "BiOutId");
                        put("database", Constants.DATA_SOURCE_GMIO);
                        put("surface", "tcgmio_bill_outlay");
                    }});
                    if(BiOutIduuid!=null){
                        int numberss=Integer.valueOf(BiOutIduuid.get("uuid").toString());
                        BiOutIdUUID = ComUtils.getLocalTrmSeqNum("zcWAT",numberss);
                    }else{
                        BiOutIdUUID = ComUtils.getLocalTrmSeqNum("zcWAT",0);
                    }
                    OutLaymap.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                    OutLaymap.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(OutLaymap);
                    OutLaymap.put("BiOutId",BiOutIdUUID);//账单编号
                    OutLaymap.put("CorId",CorIdMap.get("CorId"));//归属公司
                    OutLaymap.put("Period",1);//账期
                    OutLaymap.put("BiOutName","秘书抄表生成水费账单");//账单名称
                    OutLaymap.put("IfTemporary",0);//0否临时账单 1是
                    OutLaymap.put("BiOutType",4);//4账单类型 公共事业费
                    OutLaymap.put("PubType",1);//水费
                    OutLaymap.put("BillExplain","秘书抄表生成水费账单");//金额说明
                    OutLaymap.put("StartTime",WatHouMap.get("StaTime"));//账单生成日
                    OutLaymap.put("EndTime",WatHouMap.get("EndTime"));//账单结束日
                    OutLaymap.put("LateDay",WatHouMap.get("EndTime"));//账单最晚付款日
                    OutLaymap.put("IfAdjust",0);//当前账单是否可以调整0否
                    OutLaymap.put("StemType",3);//支出类型 3租客
                    OutLaymap.put("HouId",WatHouMap.get("HouId"));//房源id
                    OutLaymap.put("HouInfoId",WatHouMap.get("HouInfoId"));//房源详表编号
                    OutLaymap.put("CreateType",2);//账单创建人类型1系统 2 人为
                    OutLaymap.put("Applicant", ContextUtils.getUserId());//申请人
                    OutLaymap.put("Status",1);//账单状态1待支付




                    Map<String,Object> billMap = new HashMap<>();
                    String  BiIdUUID ="";//租客编号
                    Map<String, Object> BiIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                        put("uuid", "BiId");
                        put("database", Constants.DATA_SOURCE_GMIO);
                        put("surface", "tcgmio_tenant_bill");
                    }});

                    if(BiIduuid!=null){
                        int number=Integer.valueOf(BiIduuid.get("uuid").toString());
                        BiIdUUID = ComUtils.getLocalTrmSeqNum("BIWATMS",number);
                    }else{
                        BiIdUUID = ComUtils.getLocalTrmSeqNum("BIWATMS",0);
                    }
                    billMap.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                    billMap.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(billMap);
                    billMap.put("BiId",BiIdUUID);//账单编号
                    billMap.put("CorId",CorIdMap.get("CorId"));//账单归属公司
                    billMap.put("BiName","秘书抄表生成租客水费账单");//账单名称
                    billMap.put("IfTemporary",0);//是否是临时账单0否 1 是
                    billMap.put("BiType",2);//账单类型 2公共事业费
                    billMap.put("PubType",1);//公共事业费类型1水费 2电费 3燃气
                    billMap.put("BillExplain","秘书抄表生成租客水费账单");//账单金额说明
                    billMap.put("BiGenerated",WatHouMap.get("StaTime"));//账单生成日
                    billMap.put("EndTime", WatHouMap.get("EndTime"));//账单结束日
                    billMap.put("LateDay", WatHouMap.get("EndTime"));//账单最晚付款日
                    billMap.put("HouId",WatHouMap.get("HouId"));//房源编号
                    billMap.put("HouInfoId",WatHouMap.get("HouInfoId"));//房源详表编号
                    billMap.put("CreateType",2);//账单创建人类型1系统 2 人为
                    billMap.put("Create",ContextUtils.getUserId());//账单创建人
                    billMap.put("ExpTime",WatHouMap.get("EndTime"));//逾期开始时间
                    billMap.put("Status",1);//1待支付


                    if (getInfoMap==null){//只用生成唐巢支出
                        OutLaymap.put("Relation",WatmeIdUUID);//关联账单,本次抄表记录
                        OutLaymap.put("BiMoney",WatHouMap.get("BillMoney"));//账单金额
                        GasBiMoney = MapUtils.getDouble(OutLaymap,"BiMoney");
                        Integer a1 = billOwnerMapper.AddBillOwner(OutLaymap);//生成支出账单
                        if (a1>0){
                           // result.putSuccess("生成支出账单成功");
                            aaa++;
                        }else{
                            return result.putFailed("生成支出账单失败");
                        }


                    }else{//不仅要生成唐巢支出,也要生成租客账单(该房源已经出租)

                        OutLaymap.put("Relation",WatmeIdUUID);//关联账单,本次抄表记录
                        OutLaymap.put("BiMoney",WatHouMap.get("BillMoney"));//账单金额
                        OutLaymap.put("StemId",getInfoMap.get("TenId"));//支出关联人编号,有租客
                        Integer a2 = billOwnerMapper.AddBillOwner(OutLaymap);//生成支出账单
                        if (a2>0){
                           // result.putSuccess("生成支出账单成功");
                            aaa++;

                        }else{
                            return result.putFailed("生成支出账单失败");
                        }



                        //先查秘书
                        String StartTime = MapUtils.getString(getInfoMap,"StartTime");//合同的开始时间
                        Map<String,Object> mishuMap =new HashMap<>();
                        mishuMap.put("StartTime",StartTime);
                        mishuMap.put("HouId",WatHouMap.get("HouId"));
                        mishuMap.put("MeterRole",1);
                        Map<String,Object> getHouInfoGas= new HashMap<>();

                        getHouInfoGas= hoWaterMeterMapper.getHouInfoMater(mishuMap);//上次抄表人是秘书
                        if (getHouInfoGas==null){
                            mishuMap.put("MeterRole",0);
                            mishuMap.remove("StartTime");
                            getHouInfoGas = hoWaterMeterMapper.getHouInfoMater(mishuMap);//上次抄表人租赁顾问

                        }
                        //秘书查不到就差顾问





                       // Map<String,Object> getHouInfoGas = hoWaterMeterMapper.getHouInfoMater(WatHouMap);//查询上次抄表人
                        if (MapUtils.getInteger(getHouInfoGas,"MeterRole")==0){//租赁顾问

                            billMap.put("Source",WatmeIdUUID);//账单来源
                            billMap.put("TenId",getInfoMap.get("TenId"));//租客编号
                            billMap.put("BiMoney",CompuUtils.mul(CompuUtils.reduce( MapUtils.getDouble(WatHouMap,"ThisMonthRead"),MapUtils.getDouble(getHouInfoGas,"ThisMonthRead")),MapUtils.getDouble(getInfoMap,"WaterPricing")));//账单金额,每个租客本次抄表需支付金额
                            GasBiMoney = MapUtils.getDouble(billMap,"BiMoney");
                            Integer a4 =  seTenantBillMapper.addTenantBill(billMap);
                            if (a4>0){
                               // result.putSuccess("生成租客账单成功");
                                aaa++;

                                JsonResult OpenResult = zwxTenantFeign.getTenOpenId(billMap);
                                Map<String,Object> ceshiMap = (Map<String, Object>) OpenResult.get("result");
                                //推送微信模板
                                String touser=ceshiMap.get("uopid").toString();//租客的openid
                                Map<String, TemplateData> param = new HashMap<>();
                                param.put("first", new TemplateData("唐巢公寓温馨提示：尊敬的租客，您有新的待支付的水费账单。请您尽快支付。如有异议，请联系您的租赁顾问人员为您服务。\n", "#4876FF"));
                                param.put("keyword1", new TemplateData(billMap.get("BiGenerated").toString(), "#4876FF"));//账单日期
                                param.put("keyword2", new TemplateData("0", "#4876FF"));//逾期天数
                                param.put("keyword3", new TemplateData(billMap.get("BiGenerated").toString()+"-"+billMap.get("LateDay").toString(), "#4876FF"));//账单周期
                                param.put("keyword4", new TemplateData(billMap.get("BiMoney").toString(), "#4876FF"));//应缴明细
                                log.info("param:"+net.sf.json.JSONObject.fromObject(param));
                                Jsapi_ticketUtil.sendTemplate(touser, WeChatConfig.GUANMI_ID,"http://www.4006269069.net/#/allBill","#4876FF", net.sf.json.JSONObject.fromObject(param));







                            }else{
                                return result.putFailed("生成租客账单失败");
                            }


                        }else if(MapUtils.getInteger(getHouInfoGas,"MeterRole")==1){//秘书

                            billMap.put("Source",WatmeIdUUID);//账单来源
                            billMap.put("BiMoney",WatHouMap.get("BillMoney"));//账单金额,每个租客本次抄表需支付金额
                            billMap.put("TenId",getInfoMap.get("TenId"));//租客编号
                            GasBiMoney = MapUtils.getDouble(billMap,"BiMoney");
                            Integer a3 =  seTenantBillMapper.addTenantBill(billMap);
                            if (a3>0){
                                //result.putSuccess("生成租客账单成功");
                                aaa++;

                                JsonResult OpenResult = zwxTenantFeign.getTenOpenId(billMap);
                                Map<String,Object> ceshiMap = (Map<String, Object>) OpenResult.get("result");
                                //推送微信模板
                                String touser=ceshiMap.get("uopid").toString();//租客的openid
                                Map<String, TemplateData> param = new HashMap<>();
                                param.put("first", new TemplateData("唐巢公寓温馨提示：尊敬的租客，您有新的待支付的水费账单。请您尽快支付。如有异议，请联系您的租赁顾问人员为您服务。\n", "#4876FF"));
                                param.put("keyword1", new TemplateData(billMap.get("BiGenerated").toString(), "#4876FF"));//账单日期
                                param.put("keyword2", new TemplateData("0", "#4876FF"));//逾期天数
                                param.put("keyword3", new TemplateData(billMap.get("BiGenerated").toString()+"-"+billMap.get("LateDay").toString(), "#4876FF"));//账单周期
                                param.put("keyword4", new TemplateData(billMap.get("BiMoney").toString(), "#4876FF"));//应缴明细
                                log.info("param:"+net.sf.json.JSONObject.fromObject(param));
                                Jsapi_ticketUtil.sendTemplate(touser, WeChatConfig.GUANMI_ID,"http://www.4006269069.net/#/allBill","#4876FF", net.sf.json.JSONObject.fromObject(param));

                            }else{
                                return result.putFailed("生成租客账单失败");
                            }

                        }

                    }


                    Map<String,Object> GasMap = new HashMap<>();//记录燃不生成账单
                    GasMap.put("term", "2");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                    GasMap.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(GasMap);
                    GasMap.put("WameId",WatmeIdUUID);//燃气费抄表编号
                    GasMap.put("BatchId",BatchIdUUID);//批次编号
                    GasMap.put("HouId",WatHouMap.get("HouId"));//房源编号
                    GasMap.put("HouInfoId",WatHouMap.get("HouInfoId"));//房源详表编号
                    GasMap.put("IfOperaType",1);//是否整租0否1是
                    GasMap.put("LastMonthRead",WatHouMap.get("LastMonthRead"));//上次总表数
                    GasMap.put("ThisMonthRead",WatHouMap.get("ThisMonthRead"));//总表数
                    GasMap.put("StaTime",WatHouMap.get("StaTime"));//总表数
                    GasMap.put("EndTime",WatHouMap.get("EndTime"));//总表数
                    GasMap.put("MeterRole",1);//抄表人角色1 服务秘书
                    GasMap.put("BillMoney",GasBiMoney);//账单金额111111111111111111111111
                    GasMap.put("GenerateTime",GenerateTimes);//抄表日期
                    GasMap.put("Recorder", ContextUtils.getUserId());//记录人编号
                    GasMap.put("IfApportion",0);//是否需要分摊0否1是
                    GasMap.put("IfGenerate",1);//是否生成账单
                    Integer a3= hoWaterMeterMapper.addHoWaterMeter(GasMap);//新增燃气抄表记录
                    if (a3>0){
                       // result.putSuccess("新增水表抄表成功");
                        aaa++;
                    }else{
                        return result.putFailed("新增水表抄表失败");
                    }


                    if(getInfoMap==null){
                        if (aaa==2){
                            a++;
                        }else{
                            return result.putFailed("本次抄表失败");
                        }

                    }else {
                        if (aaa==3){
                            a++;
                        }else{
                            return result.putFailed("本次抄表失败");
                        }

                    }

                }
                if(a==WatHouList.size()){
                    result.putSuccess("抄表成功");
                }else{
                    return result.putFailed("抄表失败");
                }


            }
        }catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事务回滚
        } finally {
            lock.unlock();
        }
        return result;
    }

    /**
     * 管家退租查询上期水表(如果整租上期为租赁顾问或者秘书)(合租上期位置租赁顾问或者管家)
     * @param params
     * @return
     */
    @Override
    public JsonResult getLastWatLease(Map<String, Object> params) {

        JsonResult result = new JsonResult();
        return result.put(hoWaterMeterMapper.getHouInfoMater(params));
    }

}
